package com.xiaohongshu.kafkademo.handler;


import com.xiaohongshu.kafkademo.event.DataChangeEvent;
import com.xiaohongshu.kafkademo.service.UserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class DataChangeEventHandler {



    @Resource
    private UserService userService;

    @EventListener
    @Async
    public void handleUserTableChange(DataChangeEvent event) {
        if (!"user".equals(event.getTable())) {
            return;
        }

        log.info("处理用户表变更事件: 类型={}, ID={}", event.getEventType(), event.getId());

        switch (event.getEventType()) {
            case "INSERT":
                handleUserInsert(event);
                break;
            case "UPDATE":
                handleUserUpdate(event);
                break;
            case "DELETE":
                handleUserDelete(event);
                break;
        }
    }

    private void handleUserInsert(DataChangeEvent event) {
        Map<String, Object> afterData = event.getAfterData();
        log.info("用户新增事件: {}", afterData);
        
        // 业务处理示例：
        // 1. 更新缓存
        updateUserCache(event.getId(), afterData);
        
        // 2. 发送欢迎邮件
        sendWelcomeEmail(afterData);
        
        // 3. 统计用户数量
        updateUserCount(1);
    }

    private void handleUserUpdate(DataChangeEvent event) {
        Map<String, Object> beforeData = event.getBeforeData();
        Map<String, Object> afterData = event.getAfterData();
        
        log.info("用户更新事件 - ID: {}", event.getId());
        log.info("更新前: {}", beforeData);
        log.info("更新后: {}", afterData);
        
        // 检查具体哪些字段发生了变更
        beforeData.forEach((key, beforeValue) -> {
            Object afterValue = afterData.get(key);
            if (!String.valueOf(beforeValue).equals(String.valueOf(afterValue))) {
                log.info("字段 {} 发生变更: {} -> {}", key, beforeValue, afterValue);
                
                // 根据不同字段执行不同的业务逻辑
                switch (key) {
                    case "email":
                        // 邮箱变更，发送验证邮件
                        sendEmailVerification(afterValue.toString());
                        break;
                    case "username":
                        // 用户名变更，更新相关数据
                        updateRelatedData(event.getId(), afterValue.toString());
                        break;
                }
            }
        });
        
        // 更新缓存
        updateUserCache(event.getId(), afterData);
    }

    private void handleUserDelete(DataChangeEvent event) {
        Map<String, Object> beforeData = event.getBeforeData();
        log.info("用户删除事件 - ID: {}, 删除的数据: {}", event.getId(), beforeData);
        
        // 业务处理：
        // 1. 清除缓存
        clearUserCache(event.getId());
        
        // 2. 清理相关数据
        cleanupUserRelatedData(event.getId());
        
        // 3. 更新统计
        updateUserCount(-1);
    }

    @EventListener
    public void handleAllDataChange(DataChangeEvent event) {
        // 记录所有数据变更日志（用于审计）
        log.debug("数据变更审计 - 库: {}, 表: {}, 类型: {}, 时间: {}", 
                event.getDatabase(), event.getTable(), event.getEventType(), event.getExecuteTime());
    }

    // 业务处理方法示例
    private void updateUserCache(Long userId, Map<String, Object> userData) {
        log.info("更新用户缓存: userId={}", userId);
        // 这里可以实现Redis缓存更新逻辑
        // redisTemplate.opsForHash().putAll("user:" + userId, userData);
    }

    private void clearUserCache(Long userId) {
        log.info("清除用户缓存: userId={}", userId);
        // redisTemplate.delete("user:" + userId);
    }

    private void sendWelcomeEmail(Map<String, Object> userData) {
        String email = (String) userData.get("email");
        String username = (String) userData.get("username");
        log.info("发送欢迎邮件给: {} ({})", username, email);
        // 实现邮件发送逻辑
    }

    private void sendEmailVerification(String newEmail) {
        log.info("发送邮箱验证邮件到: {}", newEmail);
        // 实现邮箱验证逻辑
    }

    private void updateRelatedData(Long userId, String newUsername) {
        log.info("更新用户 {} 的相关数据，新用户名: {}", userId, newUsername);
        // 更新其他表中的相关数据
    }

    private void cleanupUserRelatedData(Long userId) {
        log.info("清理用户 {} 的相关数据", userId);
        // 清理相关表的数据
    }

    private void updateUserCount(int delta) {
        log.info("更新用户统计数量: {}", delta > 0 ? "+" + delta : delta);
        // 更新统计信息
    }
}
